package com.chenwy.example.configuration;
import com.atomikos.jdbc.AtomikosDataSourceBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import java.sql.SQLException;
/**
 * Created by Administrator on 2019/5/7.
 */
@ConfigurationProperties(prefix = "main.datasource")
@Configuration
@DependsOn("transactionManager")
@EnableJpaRepositories(basePackages = "com.chenwy.example.repository.main", entityManagerFactoryRef = "entityManagerMain")
@MapperScan(basePackages = "com.chenwy.example.dao.main",sqlSessionTemplateRef = "sqlSessionTemplateMain")
public class MainDBConfig extends DBConfigBase {


    @Autowired
    private DatabaseConfiguration databaseConfiguration;

    @Bean(name="mainDataSource",initMethod = "init",destroyMethod = "close")
    public AtomikosDataSourceBean mainDataSource() throws SQLException {
        return getAtomikosDataSource(databaseConfiguration);
    }

    @Bean(name="sqlSessionFactoryMain")
    public SqlSessionFactory sqlSessionFactoryMain(@Qualifier("mainDataSource") AtomikosDataSourceBean dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/main/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name="sqlSessionTemplateMain")
    public SqlSessionTemplate  sqlSessionTemplateMain(@Qualifier("sqlSessionFactoryMain") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }


    @Bean(name="entityManagerMain")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier("mainDataSource") AtomikosDataSourceBean dataSource){
        LocalContainerEntityManagerFactoryBean entityManagerFactory = getEntityManagerFactory(dataSource);
        return entityManagerFactory;
    }
}
